import Vue from 'vue'
import VueRouter from 'vue-router'
import store from "@/store";
import Manage from "@/views/Manage";

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component:Manage,
    redirect: "/home",
    children: [
      { path: 'home',name:"主页", component: () => import('../views/Home.vue')},
      { path: 'user',name:"用户管理", component: () => import('../views/User.vue')},
      { path: 'file',name:"文件管理", component: () => import('../views/File.vue')},
      { path: 'person', name: '个人信息', component: () => import('../views/Person')},
      { path: 'password', name: '修改密码', component: () => import('../views/Password')},
      { path: 'student', name: '学生信息管理', component: () => import('../views/Student')}
    ]
  },
  {
    path: '/about',
    name: 'About',
    component: () => import('../views/About.vue')
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login')
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/Register')
  },
  {
    path: '/**',
    name: '404',
    component: () => import('../views/404')
  }
]

const router = new VueRouter({
  mode: 'history',
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  localStorage.setItem("currentPathName", to.name)  // 设置当前的路由名称，为了在Header组件中去使用
  store.commit("setPath")  // 触发store的数据更新
  //============检测是否有token，若无则返回登录页======================
  let user = localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : null
  const isLogin = !!user
  //放行登录页和注册页
  if (to.path === '/login' || to.path === '/register') {
    next()
  }else {
    isLogin ? next() : next('/login')
  }
  //=============================================================
})

export default router
